using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using T.FAS.Runtime.Action.SPI;
using T.FAS.Runtime.Base.Entity;
using  T.ServiceFramework.ServiceGateway.Client;

namespace T.FAS.Runtime.Action.Engine
{
    /// <summary>
    /// TResponseUtil工具类
    /// </summary>
    internal class TResponseUtil
    {
        public static void ConvertTResponseToTResult(string result,bool isList, TCommonResult<JObject> tResult,TSchema schema)
        {
            try
            {
                var resultdata = JsonConvert.DeserializeObject<TResponse>(result);
                if (resultdata == null || (resultdata.state == "0" && string.IsNullOrEmpty(resultdata.errmsg)))
                    throw new FasException(ActionExecuteExceptionCode.SGActionExecuteReturnDataTypeError,CommonStringClassEngine.TResponseUtil_SGReturnDataStructureInvalid);
                JToken dataContent = null;
                if (resultdata != null)
                {
                    if (resultdata.state == "0")
                    {
                        throw new FasException(ActionExecuteExceptionCode.SGActionExecuteError, resultdata.errmsg);
                    }
                    if (resultdata.data != null)
                    {
                        JObject jdata = resultdata.data as JObject;
                        if (jdata != null)
                        {
                            if (isList)
                            {
                                var totalCount = Convert.ToInt32(jdata["total"]);
                                dataContent = jdata["rows"];
                                if (dataContent == null)
                                {
                                    bool isTryGetDataSussecc = false;
                                    //尝试增加一层的解析，用于应对业务自定义的返回值结构
                                    if (jdata["data"] != null)
                                    {
                                        var userDefineData = jdata["data"] as JObject;
                                        if (userDefineData != null)
                                        {
                                            totalCount = Convert.ToInt32(userDefineData["total"]);
                                            dataContent = userDefineData["rows"];
                                            isTryGetDataSussecc = true;
                                        }
                                    }
                                    if (!isTryGetDataSussecc)
                                        throw new FasException(ActionExecuteExceptionCode.SGActionExecuteReturnDataTypeError, CommonStringClassEngine.TResponseUtil_ConvertTResponseToTResult1);
                                }
                                tResult.Count = totalCount; 
                                var listRecord = new TArray<JObject>(schema.Entity);
                                foreach (var item in dataContent)
                                {
                                    listRecord.Add(item as JObject);
                                }
                                tResult.List = listRecord;
                            }
                            else
                            {
                                dataContent = jdata;
                                tResult.Record = jdata;
                            }
                        }
                        else
                        {
                            JArray jarray = resultdata.data as JArray;
                            if (jarray != null)
                            {
                                if (isList)
                                {
                                    var listRecord = new TArray<JObject>(schema.Entity);
                                    foreach (var item in jarray)
                                    {
                                        listRecord.Add(item as JObject);
                                    }
                                    tResult.List = listRecord;
                                    tResult.Count = jarray.Count();
                                }
                                else
                                {
                                    tResult.Record = jarray.FirstOrDefault() as JObject;
                                }
                            }
                            else
                            {
                                throw new FasException(ActionExecuteExceptionCode.ActionExecuteEngineExecuteError,CommonStringClassEngine.TResponseUtil_UnidentifiedSGReturnValueType);
                            }
                        }
                    }
                    else
                    {
                        dataContent = null;
                    }
                }
            }
            catch (Exception ex)
            {
                var errMsg = "";
                if (!string.IsNullOrEmpty(ex.Message))
                    errMsg = ex.Message;
                else if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message))
                    errMsg = ex.Message;
                else
                    errMsg = ex.InnerException == null ? Convert.ToString(ex) : Convert.ToString(ex.InnerException);
                throw new FasException(ActionExecuteExceptionCode.SGActionExecuteError, errMsg);
            }
        }

        public static void ConvertTResponseToTResult(string result, bool isList, TCommonResult<TRecord> tResult, TSchema schema)
        {
            try
            {
                var resultdata = JsonConvert.DeserializeObject<TResponse>(result);
                if (resultdata == null || (resultdata.state == "0" && string.IsNullOrEmpty(resultdata.errmsg)))
                    throw new FasException(ActionExecuteExceptionCode.SGActionExecuteReturnDataTypeError, CommonStringClassEngine.TResponseUtil_SGReturnDataStructureInvalid);
                JToken dataContent = null;
                if (resultdata != null)
                {
                    if (resultdata.state == "0")
                    {
                        throw new FasException(ActionExecuteExceptionCode.SGActionExecuteError, resultdata.errmsg);
                    }
                    if (resultdata.data != null)
                    {
                        JObject jdata = resultdata.data as JObject;
                        if (jdata != null)
                        {
                            if (isList)
                            {
                                var totalCount = Convert.ToInt32(jdata["total"]);
                                tResult.Count = totalCount;
                                dataContent = jdata["rows"];
                                var listRecord = new TArray<TRecord>(schema.Entity);
                                foreach (var item in dataContent)
                                {
                                    listRecord.Add(new TRecord(new Dictionary<string, object>() { { BasicTypeData.DefaultPropertyName, item } }));
                                }
                                tResult.List = listRecord;
                            }
                            else
                            {
                                dataContent = jdata;
                                tResult.Record = new TRecord(new Dictionary<string, object>() { { BasicTypeData.DefaultPropertyName,jdata} }); 
                            }
                        }
                        else
                        {
                            JArray jarray = resultdata.data as JArray;
                            if (jarray != null)
                            {
                                if (isList)
                                {
                                    var listRecord = new TArray<TRecord>(schema.Entity);
                                    foreach (var item in jarray)
                                    {
                                        listRecord.Add(new TRecord(new Dictionary<string, object>() { { BasicTypeData.DefaultPropertyName, item } }));
                                    }
                                    tResult.List = listRecord;
                                    tResult.Count = jarray.Count();
                                }
                                else
                                {
                                    tResult.Record = new TRecord(new Dictionary<string, object>() { { BasicTypeData.DefaultPropertyName, jarray.FirstOrDefault() as JObject } }) ;
                                }
                            }
                            else
                            {
                                throw new FasException(ActionExecuteExceptionCode.ActionExecuteEngineExecuteError, CommonStringClassEngine.TResponseUtil_UnidentifiedSGReturnValueType);
                            }
                        }
                    }
                    else
                    {
                        dataContent = null;
                    }
                }
            }
            catch (Exception ex)
            {
                var errMsg = "";
                if (!string.IsNullOrEmpty(ex.Message))
                    errMsg = ex.Message;
                else if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message))
                    errMsg = ex.Message;
                else
                    errMsg = ex.InnerException == null ? Convert.ToString(ex) : Convert.ToString(ex.InnerException);
                throw new FasException(ActionExecuteExceptionCode.SGActionExecuteError, errMsg);
            }
        }
    }
}
